﻿using AutoMapper;
using B.S.BaseData.Domain;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.ReadAPI.Applications.Commands.AccountCommand;
using B.S.BaseData.ReadAPI.Dtos;
using MD5Hash;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Text;

namespace B.S.BaseData.ReadAPI.Applications.CommandHandlers.AccountCommandHandler
{
    public class LoginHandler:IRequestHandler<LoginCommand,ApiResult<LoginAccountRespDto>>
    {
        IBaseRepository<Account> accountrepositoy;
        ILogger<LoginHandler> logger;
        IMapper mapper;
        private readonly TokenHelper tokenHelper;

        public LoginHandler(IBaseRepository<Account> accountrepositoy, ILogger<LoginHandler> logger, IMapper mapper, TokenHelper tokenHelper)
        {
            this.accountrepositoy = accountrepositoy;
            this.logger = logger;
            this.mapper = mapper;
            this.tokenHelper = tokenHelper;
        }

        public async Task<ApiResult<LoginAccountRespDto>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new ApiResult<LoginAccountRespDto>();

                var list = await accountrepositoy.GetAsync(d => d.LoginName.Equals(request.LoginName));
                if(list==null)
                {
                    result.msg = "用户名不存在";
                    return result;
                }
                var a = request.LoginPwd.GetMD5();
                if(list.LoginPwd.ToLower() != a.ToLower())
                {
                    result.msg = "用户名或密码有误";
                    return result;
                }

                var data = mapper.Map<LoginAccountRespDto>(list);
                data.Token = tokenHelper.CreateJwtToken(list);
                result.data = data;
                result.success(data);
                result.IsSuc=true;

                return result;
            }
            catch (Exception ex)
            {
                logger.LogError("用户登录出错" + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 生成 JWT Token（令牌）
        /// </summary>
        /// <returns></returns>
        private string CreateTokenString()
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }

    }
}
